﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using System.Windows.Forms;

namespace RexToy.UI.WinForm.Pmlx
{
    class EmbedLocator : IPmlxFileLocator
    {
        public PmlxDoc ReadPmlxFile(UserControl uc)
        {
            string name = uc.GetType().Name + PmlxConstant.UC_EXTENSION;
            Assembly assembly = uc.GetType().Assembly;
            foreach (var resName in assembly.GetManifestResourceNames())
            {
                if (resName.EndsWith(name))
                {
                    using (Stream stream = assembly.GetManifestResourceStream(resName))
                    {
                        return PmlxDoc.Load(stream);
                    }
                }
            }
            return null;
        }

        public PmlxDoc ReadPmlxFile(Form f)
        {
            string name = f.GetType().Name + PmlxConstant.FORM_EXTENSION;
            Assembly assembly = f.GetType().Assembly;
            foreach (var resName in assembly.GetManifestResourceNames())
            {
                if (resName.EndsWith(name))
                {
                    using (Stream stream = assembly.GetManifestResourceStream(resName))
                    {
                        return PmlxDoc.Load(stream);
                    }
                }
            }
            return null;
        }

        public bool ExistPmlxFile(UserControl uc)
        {
            string name = uc.GetType().Name + PmlxConstant.UC_EXTENSION;
            Assembly assembly = uc.GetType().Assembly;
            foreach (var resName in assembly.GetManifestResourceNames())
            {
                if (resName.EndsWith(name))
                    return true;
            }
            return false;
        }

        public bool ExistPmlxFile(Form f)
        {
            string name = f.GetType().Name + PmlxConstant.FORM_EXTENSION;
            Assembly assembly = f.GetType().Assembly;
            foreach (var resName in assembly.GetManifestResourceNames())
            {
                if (resName.EndsWith(name))
                    return true;
            }
            return false;
        }
    }
}
